/* 
* @Author: Turbidsoul Chen
* @Date:   2016-12-07 17:04:48
* @Last Modified by:   Turbidsoul Chen
* @Last Modified time: 2017-01-04 15:47:58
*/

import React, { Component } from 'react';
import {Link} from 'react-router';


const isModifiedEvent = (event) =>
  !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);

export default class LinkContainer extends Component {
  static propTypes = {
    to: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.object
    ]).isRequired,
    onClick: React.PropTypes.func,
    active: React.PropTypes.bool.isRequired,
    children: React.PropTypes.node.isRequired,
    action: React.PropTypes.oneOf(['push', 'replace']),
    onlyActiveOnIndex: React.PropTypes.bool.isRequired,
    linkComponent: React.PropTypes.any.isRequired,
    className: React.PropTypes.string,
    activeClassName: React.PropTypes.string,
    replace: React.PropTypes.boolean
  };

  static contextTypes = {
    router: React.PropTypes.object
  };

  static defaultProps = {
    action: 'push',
    onlyActiveOnIndex: false,
    linkComponent: Link,
    active: false,
    activeClassName: 'am-active'
  };

  _onClick(e) {
    const {children, onClick} = this.props;
    if(children.props.onClick) {
      children.props.onClick(e);
    }
    if(onClick) {
      onClick(e);
    }

    if(!e.defaultPrevented && event.button === 0 && !isModifiedEvent(e)) {
      e.preventDefault();
      let history = this.context.router.history;
      let {replace, to} = this.props;
      if(replace) {
        history.replace(to);
      } else {
        history.push(to);
      }
    }
  }
  render() {
    const {
      children, to, active, onlyActiveOnIndex, linkComponent, className,
      activeClassName
    } = this.props;
    const linkProps = {to};
    const router = this.context.router;
    let isActive = active || router.isActive(to, onlyActiveOnIndex);
    return React.cloneElement(
      React.Children.only(children),
      {
        linkComponent,
        linkProps,
        className: className,
        active: isActive,
        onClick: ::this._onClick
      }
    );
  }
}

